package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.InfoMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.RegisterNewUserEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.RegisterNewUserListener;
import ua.org.nuos.sdms.clientgui.client.util.ComponentUtil;
import ua.org.nuos.sdms.clientgui.client.view.LoginWindow;
import ua.org.nuos.sdms.clientgui.client.view.RegisterNewUserWindow;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.enums.Role;
import ua.org.nuos.sdms.middle.util.exception.DuplicateEmailException;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 26.02.12
 * Time: 18:14
 * To change this template use File | Settings | File Templates.
 */
public class RegistrationNewUserHandler implements RegisterNewUserListener {
    @Override
    public void register(RegisterNewUserEvent event) {
        try {
            AppProxy.getInstance().getServiceLocator().getRegistrationBean()
                    .registerNewUser(event.getUser(), Role.CLIENT);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(
                    new InfoMessageEvent(String.format(Messages.REGISTRATION_SUCCESS, event.getUser().getEmail())));
            ComponentUtil.closeWindow(RegisterNewUserWindow.ID);
            ComponentUtil.closeWindow(LoginWindow.ID);
        } catch (DuplicateEmailException e) {
            Logger.getAnonymousLogger().log(Level.WARNING, "Cant register new user. Duplicate email.", e);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(
                    new ErrorMessageEvent(String.format(Messages.DUPLICATE_EMAIL_ERROR, event.getUser().getEmail())));
        } catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.WARNING, "Cant register new user", e);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.REGISTER_NEW_USER_FAILED));
        }
    }
}
